//
// Created by root on 24-7-21.
//
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include "./include/readfile.h"
#include "./include/hand_error.h"

static struct sockaddr_in get_sockaddr_in(unsigned short int port, char * ip) {
    struct sockaddr_in s;
    s.sin_port = htons(port);
    // if (ip) {
        // s.sin_addr.s_addr = inet_addr(ip);
    // }else {
        s.sin_addr.s_addr = htonl(INADDR_ANY);
    // }
    s.sin_family = PF_INET;
    bzero(&(s.sin_zero), 8);
    return s;
}

static struct sockaddr *trans_sockaddr_in_to_sockaddr(struct sockaddr_in *s) {
    return (struct sockaddr *) s;
}



int get_server_socket(unsigned short port,char * addr) {


    int fd = socket(AF_INET,SOCK_STREAM, 0);
    if (fd == -1) {
        myerror("can't create socket");
    }
    int reuse = 1;
    if (setsockopt(fd,SOL_SOCKET,SO_REUSEADDR, (char *) &reuse, sizeof(int)) == -1) {
        char *msg = "can't setsocketopt";
        myerror(msg);
    };
    printf("SUCCESS:%-20s%-10d\n", "sockfd", fd);
    struct sockaddr_in s = get_sockaddr_in(port, addr);
    struct sockaddr *s_addr = trans_sockaddr_in_to_sockaddr(&s);
    if (bind(fd, s_addr, sizeof(struct sockaddr)) == -1) {
        myerror("can't bind port");
    };
    printf("SUCCESS:%-20s%-10d\n", "bind", port);
    int query_len = 10;
    if (listen(fd, query_len) == -1) {
        myerror("can't listen query_len");
    };
    printf("SUCCESS:%-20s%-10d\n", "listenquery", query_len);
    return fd;
}